package com.winit.commons.zentao;

import com.alibaba.fastjson.JSONObject;
import com.winit.commons.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class ZenTaoUtil {

    private static Logger log = LoggerFactory.getLogger(ZenTaoUtil.class);

    private static String sessionName = "";
    private static String sessionID = "";

    private static Boolean isUseZenTao = false;
    private static String zentaoUrl = null;
    private static String zentaoUserName = null;
    private static String zentaoPassword = null;
    private static String zentaoGetSessionUrl = null;
    private static String zentaoUserLoginUrl = null;
    private static String zentaoProductListUrl = null;

    static {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("application.properties");

            sessionName = properties.getProperty("session_name");
            sessionID = properties.getProperty("session_id");

            isUseZenTao = Boolean.parseBoolean(properties.getProperty("is_use_zentao"));
            zentaoUrl = properties.getProperty("zentao_url");
            zentaoGetSessionUrl = properties.getProperty("zentao_get_session_url");
            zentaoUserLoginUrl = properties.getProperty("zentao_user_login_url");
            zentaoUserName = properties.getProperty("zentao_username");
            zentaoPassword = properties.getProperty("zentao_password");

            zentaoProductListUrl = properties.getProperty("zentao_product_list_url");
            if (isUseZenTao) {
                doZenTaoLogin();
            }
        } catch (Exception e) {
            log.error("初始化zentaoUtil异常。", e);
        }

    }

    /**
     * 拼接请求的url
     *
     * @param url
     * @return
     */
    private static String _getUrl(String url) {
        StringBuffer u = new StringBuffer();
        u.append(zentaoUrl).append(url);
        if (url.equals(zentaoGetSessionUrl)) {
            return u.toString();
        }
        if (url.contains("?")) {
            u.append("&").append(sessionName).append("=").append(sessionID);
        } else {
            u.append("?").append(sessionName).append("=").append(sessionID);
        }
        return u.toString();
    }

    private static JSONObject doPost(String url) {
        if (StringUtils.isEmpty(sessionID)) {
            log.error("com.winit.commons.util.ZenTaoUtil.doPost zentao sessionID is null . url=" + url);
            return null;
        }
        return _doPost(url);
    }

    private static JSONObject _doPost(String url) {
        String u = _getUrl(url);
        if (!u.contains("f=login")) {
            log.info("com.winit.commons.util.ZenTaoUtil.doPost url=" + u);
        }
        JSONObject json = null;
        try {
            json = HttpClientUtil.doPostForJson(u, null);
            if ("off".equals(json.getJSONObject("data").get("keepLogin")) && "Login".equals(json.getJSONObject("data").get("title"))) {
                if (!isUseZenTao) {
                    return null;
                }
                log.info("com.winit.commons.util.ZenTaoUtil.doPost login timeout. do login again.");
                doZenTaoLogin();
                json = HttpClientUtil.doPostForJson(u, null);
            }
        } catch (Exception e) {
            log.error("com.winit.commons.util.ZenTaoUtil.doPost 异常.url=" + u, e);
        }
        return json;
    }

    private static void doZenTaoLogin() {
        JSONObject session = _doPost(zentaoGetSessionUrl);
        sessionID = session.getJSONObject("data").getString("sessionID");
        sessionName = session.getJSONObject("data").getString("sessionName");
        _doPost(zentaoUserLoginUrl + "&account=" + zentaoUserName + "&password=" + zentaoPassword);
    }

    public static List getProductList() {
        JSONObject object = doPost(zentaoProductListUrl);
        if (null == object || !"success".equals(object.getString("status"))) {
            return new ArrayList();
        }
        return object.getJSONArray("data");
    }

    public static void main(String[] args) {
        ZenTaoUtil.getProductList();
    }
}
